#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

void catch_child(int signo){
    pid_t wpid;
    int status;
    while((wpid = waitpid(-1,&status,0)) != -1){ //循环回收子进程，防止僵尸进程
        if(WIFEXITED(status)){
            printf("---catch child id %d, ret = %d\n",wpid,WEXITSTATUS(status));
        }
    }
}


int main(){
    pid_t pid;
    int i ;
    for (i = 0; i < 10 ; i++){
        if ((pid = fork()) == 0){ // 创建多个子进程
            break;
        }
    }

    if (i == 10){
        struct sigaction act;
        act.sa_handler = catch_child; //设置回调函数
        sigemptyset(&act.sa_mask);   //设置捕捉函数执行期间屏蔽字
        act.sa_flags = 0;     //设置默认属性，本信号自动屏蔽

        sigaction(SIGCHLD,&act,NULL); //注册信号捕捉函数

        printf("I'm parent , pid = %d\n",getpid());

        while(1);
    }else {
        printf("I'm child, pid = %d\n",getpid());
        return i;
    }
    return 0;
}